package com.everbest.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.everbest.common.config.Global;
import com.everbest.common.json.JSON;
import com.everbest.common.json.JSONObject;
import com.everbest.common.utils.http.HttpUtils;

/**
 * 获取地址类
 *
 */
public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    public static final String IP_URL = "http://api.map.baidu.com/location/ip";

    public static String getRealAddressByIP(String ip) {
        String address = "XX XX";

        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        if (Global.isAddressEnabled()) {
            String rspStr = HttpUtils.sendPost(IP_URL, "ak=rSThOWqhKGvcVhUVXnRDtsPxUVaIra81&ip=" + ip);
            if (StringUtils.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return address;
            }
            JSONObject obj;
            try {
                obj = JSON.unmarshal(rspStr, JSONObject.class);
                JSONObject data = obj.getObj("content");
                JSONObject address_detail = data.getObj("address_detail");
                String region = unicodeToCn(address_detail.getStr("province"));
                String city = unicodeToCn(address_detail.getStr("city"));
                address = region + " " + city;
            } catch (Exception e) {
                log.error("获取地理位置异常 {}", ip, e);
            }
        }
        return address;
    }

    private static String unicodeToCn(String unicode) {
        /** 以 \ u 分割，因为java注释也能识别unicode，因此中间加了一个空格 */
        String[] strs = unicode.split("\\\\u");
        String returnStr = "";
        // 由于unicode字符串以 \ u 开头，因此分割出的第一个字符是""。
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char)Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }
}
